//
//  ReplaceMethodViewController.swift
//  MyDemoSwift
//
//  Created by 张鑫 on 2021/11/10.
//  Copyright © 2021 张鑫. All rights reserved.
//

import UIKit

class ReplaceMethodViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //现在我们要替换数数函数的实现，给他之前和之后加上点广告语。

        //拿到method
        let methond = class_getInstanceMethod(Person.self, #selector(Person.countNumber(toValue:)))
        //通过method拿到imp， imp实际上就是一个函数指针
        let oldImp = method_getImplementation(methond!)
        //由于IMP是函数指针，所以接收时需要指定 @convention(c)
        typealias Imp  = @convention(c) (Person, Selector, NSNumber) -> Void
        //将函数指针强转为兼容函数指针的闭包
        let oldImpBlock = unsafeBitCast(oldImp, to: Imp.self)

        //imp_implementationWithBlock的参数需要的是一个oc的block，所以需要指定convention(block)
        let newFunc:@convention(block) (Person, NSNumber) -> Void = {
            (sself,  toValue) in
            print("数之前， 祝大家新年快乐")
            oldImpBlock(sself, #selector(Person.countNumber(toValue:)), toValue)
            print("数之后， 祝大家新年快乐")
        }


        let imp = imp_implementationWithBlock(unsafeBitCast(newFunc, to: AnyObject.self))


        method_setImplementation(methond!, imp)

        let person = Person()
        person.countNumber(toValue: 50)

        
    }
    

    class Person:NSObject {
        //数  数字
        @objc dynamic func countNumber(toValue:Int){
            for value in 0...toValue{
                print(value)
            }
        }
    }
    
}
